package purchase

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// Rate /** 海关汇率
func rate(r *gin.RouterGroup) {
	rate := r.Group("/rate")
	{
		rate.POST(sql.RequestAdd, rateAdd)
		rate.POST(sql.RequestUpdate, rateUpdate)
		rate.GET(sql.RequestList, rateList)
		rate.GET(sql.RequestData, rateDate)
		rate.GET(sql.RequestDelete, rateDelete)
	}
}

func rateAdd(c *gin.Context) {
	sql.HttpAdd(c, &model.ExchangeRate{}, nil)
}

func rateUpdate(c *gin.Context) {
	sql.HttpUpdates(c, &model.ExchangeRate{}, nil)
}

func rateDelete(c *gin.Context) {
	sql.HttpDeleteById(c, &model.ExchangeRate{})
}

func rateDate(c *gin.Context) {
	sql.HttpHandle(sql.GET, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		bean := new(model.ExchangeRate)
		date := c.Query("date")
		types := c.Query("type")
		db = db.Where("date = ?", date).First(&bean)
		if bean != nil {
			if types == "dollar" {
				return db, bean.Dollar
			} else if types == "euro" {
				return db, bean.Euro
			}
		}
		return db, nil
	})
}

func rateList(c *gin.Context) {
	sql.HttpList(c, &[]model.ExchangeRate{}, func(db *gorm.DB) *gorm.DB {
		db = db.Order("date DESC")
		return db
	})
}
